package ui;

import java.awt.Component;
import java.io.File;

import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JList;
import javax.swing.filechooser.FileSystemView;

import bean.Files;

/**
 * ListCellRenderer文件列表单元格渲染器，用于显示文件图标
 */
class FileListCellRenderer extends DefaultListCellRenderer {
    @Override
    public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        
        if (value instanceof Files) {
            Files file = (Files) value;
            setText(file.getFileName());
            
            // 获取文件图标
            if (file.getFilePath() != null && !file.getFilePath().isEmpty()) {
                File f = new File(file.getFilePath());
                if (f.exists()) {
                    setIcon(getSmallIcon(f));
                }
            }
        }
        return this;
    }

    /**
     * 获取小图标
     * @param f 文件对象
     * @return 图标对象
     */
    private Icon getSmallIcon(File f) {
        if (f != null && f.exists()) {
            FileSystemView fsv = FileSystemView.getFileSystemView();
            return fsv.getSystemIcon(f);
        }
        return null;
    }
}
